<template>
  <el-card class="card">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-button type="primary" plain @click="addDialogFormVisible = true"
      >添加角色</el-button
    >
    <el-table border class="mt-15" :data="roleList" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <!-- <div>tag</div> -->

          <el-row
            v-for="firstChildren in scope.row.children"
            :key="firstChildren.id"
          >
            <el-col :span="4">
              <el-tag
                closable
                @close="deleteRight(scope.row, firstChildren.id)"
                >{{ firstChildren.authName }}</el-tag
              >
              <i
                class="el-icon-arrow-right"
                v-if="firstChildren.children.length !== 0"
              ></i>
            </el-col>

            <el-col :span="20">
              <el-row
                v-for="secondChildren in firstChildren.children"
                :key="secondChildren.id"
              >
                <el-col :span="4">
                  <el-tag
                    closable
                    type="success"
                    @close="deleteRight(scope.row, secondChildren.id)"
                    >{{ secondChildren.authName }}</el-tag
                  >
                  <i
                    class="el-icon-arrow-right"
                    v-if="secondChildren.children.length !== 0"
                  ></i>
                </el-col>
                <el-col :span="20">
                  <el-tag
                    closable
                    type="warning"
                    v-for="thirdChildren in secondChildren.children"
                    :key="thirdChildren.id"
                    @close="deleteRight(scope.row, thirdChildren.id)"
                  >
                    {{ thirdChildren.authName }}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" prop="roleName" width="165px">
      </el-table-column>
      <el-table-column label="描述" prop="roleDesc" width="330px">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            plain
            icon="el-icon-edit"
            @click="showEditDialog(scope.row)"
          ></el-button>
          <el-button
            size="mini"
            type="danger"
            plain
            icon="el-icon-delete"
            @click="deleteRole(scope.row)"
          ></el-button>
          <el-button
            size="mini"
            type="warning"
            plain
            icon="el-icon-check"
            title="授权角色"
            @click="showDialog(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="授权角色" :visible.sync="dialogFormVisible">
      <div class="tree-container">
        <el-tree
          :data="rightList"
          show-checkbox
          ref="tree"
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="selectedRights"
          :props="defaultProps"
        >
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitGrant">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加角色" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" ref="addForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleSubmit(addForm)"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog title="修改角色" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" ref="addForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getRoleList,
  deleteRoleRight,
  getRightList,
  grantRoleRight,
  addRole,
  editRole,
  deleteRoles
} from "../../api/index";

export default {
  name: "",
  data() {
    return {
      // 授权角色
      dialogFormVisible: false,
      roleList: [],
      rightList: [],
      currentRole: {},
      selectedRights: [],
      defaultProps: {
        children: "children", // // 树形组件展示的数据源
        label: "authName" // 树形组件显示的标题字段
      },

      // 添加角色
      addDialogFormVisible: false,
      addForm: {
        roleName: "",
        roleDesc: ""
      },

      // 修改角色
      editDialogFormVisible: false,
      editForm: {
        roleName: "",
        roleDesc: "",
        id: ""
      }
    };
  },
  watch: {},
  props: {},
  components: {},
  computed: {},
  beforeMount() {
    this.initGetRolesList();
  },
  methods: {
    async showDialog(row) {
      this.selectedRights = [];
      this.dialogFormVisible = true;
      this.currentRole = row;

      this.checkNode(row, this.selectedRights);
      console.log(this.selectedRights);

      let { data, meta } = await getRightList({ type: "tree" });
      if (meta.status === 200) return (this.rightList = data);
      return this.$message.error(meta.msg);
    },

    async initGetRolesList() {
      let { data, meta } = await getRoleList();
      if (meta.status == 200) this.roleList = data;
    },

    async deleteRight(scope, id) {
      let { data, meta } = await deleteRoleRight({
        roleId: scope.id,
        rightId: id
      });
      //   console.log(meta);
      if (meta.status === 200) {
        scope.children = data;
      } else {
        this.$message({
          type: "error",
          message: meta.msg
        });
      }
    },

    checkNode(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item => {
        return this.checkNode(item, arr);
      });
    },

    async submitGrant() {
      let rids = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys()
      ].join(",");
      let params = { roleId: this.currentRole.id, rids: rids };
      let { data, meta } = await grantRoleRight(params);
      if (meta.status === 200) {
        this.dialogFormVisible = false;
        this.$message.success("更新成功");
        this.initGetRolesList();
      } else {
        this.$message.error(meta.msg);
      }
    },

    async addRoleSubmit(form) {
      if (!form.roleName || !form.roleDesc)
        return this.$message.error("不能为空");

      let { data, meta } = await addRole(form);

      if (meta.status === 201) {
        this.$message.success("创建成功");
        this.addDialogFormVisible = false;
        this.$nextTick(() => {
          this.initGetRolesList();
        });
      } else {
        this.$message.error(meta.msg);
      }
    },

    showEditDialog(row) {
      this.editDialogFormVisible = true;
      this.editForm.roleName = row.roleName;
      this.editForm.roleDesc = row.roleDesc;
      this.editForm.id = row.id;
    },

    async editRoleSubmit() {
      let { data, meta } = await editRole(this.editForm);
      if (meta.status === 200) {
        this.$message.success("修改成功");
        this.editDialogFormVisible = false;
        this.$nextTick(() => {
          this.initGetRolesList();
        });
      } else {
        this.$message.error(meta.msg);
      }
    },

    deleteRole(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let { data, meta } = await deleteRoles({ id: row.id });

          if (meta.status === 200) {
            this.$message.success("删除成功");
            this.$nextTick(() => {
              this.initGetRolesList();
            });
          } else {
            this.$message.error(meta.msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  },
  filters: {}
};
</script>

<style scoped lang="scss">
.roles {
  .el-tag {
    margin-right: 5px;
    margin-bottom: 5px;
  }
  .tree-container {
    height: 300px;
    overflow: auto;
  }
}
</style>
